# -*- coding: utf-8 -*-
'''
Created on Jul 2, 2014

@author: LONG HOANG GIANG
'''
import sqlite3
import os
import cStringIO
import gzip
import json

def compressStr(inputStr):
    zbuf = cStringIO.StringIO()
    zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)
    zfile.write(inputStr)
    zfile.close()
    return zbuf.getvalue()

def convert(source, destination):
    if not os.path.exists(source):
        print 'Error: file {0} not found'.format(source)
        return
    
    connection_src = sqlite3.connect(source)
    cursor1 = connection_src.cursor()
    cursor1.execute("SELECT * FROM udv_story")
    rows = cursor1.fetchall()
    
    connection_dest = sqlite3.connect(destination)
    cursor2 = connection_dest.cursor()
    cursor2.execute("CREATE TABLE IF NOT EXISTS udv_content('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'hash' VARCHAR(32), 'name' VARCHAR(200), 'content' BLOB, 'is_header' INTEGER DEFAULT 0)")
    cursor2.execute("CREATE INDEX IF NOT EXISTS hash_index ON udv_content(hash)")
    cursor2.execute("CREATE INDEX IF NOT EXISTS id_index ON udv_content(id)")
    
    for row in rows:
        print row[2].encode('utf-8')
        cursor2.execute("INSERT INTO udv_content('name', 'content') VALUES(?, ?)", [row[2], buffer(compressStr(json.dumps(row[3])))])
        
    cursor1.close()
    connection_src.close()
    cursor2.close()
    connection_dest.commit()
    connection_dest.close()

def convertnew(source, destination):
    if not os.path.exists(source):
        print 'Error: file {0} not found'.format(source)
        return
    if os.path.exists(destination):
        os.unlink(destination)
    connection_src = sqlite3.connect(source)
    cursor1 = connection_src.cursor()
    cursor1.execute("SELECT * FROM udv_story")
    rows = cursor1.fetchall()
    connection_dest = sqlite3.connect(destination)
    cursor2 = connection_dest.cursor()
    cursor2.execute("CREATE TABLE IF NOT EXISTS udv_content('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'hash' VARCHAR(32), 'name' VARCHAR(200), 'content' BLOB, 'is_header' INTEGER DEFAULT 0)")
    cursor2.execute("CREATE INDEX IF NOT EXISTS hash_index ON udv_content(hash)")
    cursor2.execute("CREATE INDEX IF NOT EXISTS id_index ON udv_content(id)")
    for row in rows:
        print row[2].encode('utf-8')
        cursor2.execute("INSERT INTO udv_content('name', 'content') VALUES(?, ?)", [row[2], buffer(row[3])])
    cursor1.close()
    connection_src.close()
    cursor2.close()
    connection_dest.commit()
    connection_dest.close()

if __name__ == '__main__':
    
    print '> Start convert database'
    
    sourcePath = raw_input("Enter source database: ")
    destPath = raw_input("Enter output database: ")
    schemaType = raw_input("Schema Type: ")
    if sourcePath != '' and destPath != '':
        destPath = "/longhoanggiang/database/{0}".format(destPath)
        if os.path.exists(destPath):
            os.unlink(destPath)
        
        if (schemaType == 1):
            convert(sourcePath, destPath)
        else:
            convertnew(sourcePath, destPath)
        print '> Finished convert database'
    else:
        print 'Source path and Dest path not NULL'
    
#     parser = argparse.ArgumentParser()
#     parser.add_argument("-i", "--input", help="database convert to new database")
#     parser.add_argument("-o", "--output", help="database output", default="data.new")
#     args = parser.parse_args()
#     
#     try:
#         sourcePath = args.input
#         destPath = args.output
#         if sourcePath == None or sourcePath == '': raise Exception, 'source path not null'
#         if os.path.exists(destPath):
#             os.unlink(destPath)
#         convert(sourcePath, destPath)
#         print '> Finished convert database'
#         
#     except:
# #         traceback.print_exc()
#         parser.print_help()
    
    print '> Code by longhoanggiang'
    os._exit(1)
    
    
    